package com.study.test.demo.observer.mouseevent.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 抽象的被观察者
 *
 * @Author hupengming
 * @ClassName EventContext
 * @Date 2023-03-14  15:24
 * @Version 1.0
 */
public abstract class EventContext {

    private Map<String, Event> eventMap = new HashMap<>();

    /**
     * 添加观察者
     *
     * @param eventType
     * @param target
     * @param callback
     */
    public void addListener(String eventType, EventListener target, Method callback) {
        eventMap.put(eventType, new Event(target, callback));
    }

    public void addListener(String eventType, EventListener target) {

        try {
            this.addListener(eventType, target, target.getClass().getMethod("on" + toUpperFirstCase(eventType), Event.class));
        } catch (NoSuchMethodException e) {
            return;
        }
    }

    private String toUpperFirstCase(String eventType) {
        char[] ch = eventType.toCharArray();
        ch[0] -= 32;
        return String.valueOf(ch);
    }

    private void trigger(Event event) {

        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try {
            if (event.getCallback() != null) {
                event.getCallback().invoke(event.getTarget(), event);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void trigger(String eventType) {
        if (!this.eventMap.containsKey(eventType)) {
            return;
        }
        trigger(this.eventMap.get(eventType).setTrigger(eventType));
    }
}
